﻿using JT808.Protocol.Enums;
using JT808.Protocol.Exceptions;
using JT808.Protocol.Extensions;
using JT808.Protocol.MessageBody;
using System;

namespace JT808.Protocol.Formatters.MessageBodyFormatters
{
    public class JT808_0x0701_Formatter : IJT808Formatter<JT808_0x0701>
    {
        public JT808_0x0701 Deserialize(ReadOnlySpan<byte> bytes, out int readSize)
        {
            int offset = 0;
            JT808_0x0701 jT808_0X0701 = new JT808_0x0701
            {
                ElectronicWaybillLength = JT808BinaryExtensions.ReadUInt32Little(bytes, ref offset)
            };
            jT808_0X0701.ElectronicContent = bytes.Slice(offset, (int)jT808_0X0701.ElectronicWaybillLength).ToArray();
            readSize = offset + jT808_0X0701.ElectronicContent.Length;
            return jT808_0X0701;
        }

        public int Serialize(ref byte[] bytes, int offset, JT808_0x0701 value)
        {
            object obj = JT808FormatterExtensions.GetFormatter(value.ElectronicContentObj.GetType());
            // 需要反着来，先序列化数据体（由于位置汇报数据体长度为4个字节，所以先偏移4个字节），再根据数据体的长度设置回去
            int tmpOffset = JT808FormatterResolverExtensions.JT808DynamicSerialize(obj, ref bytes, offset + 4, value.ElectronicContentObj);
            JT808BinaryExtensions.WriteUInt32Little(bytes, offset, (ushort)(tmpOffset - offset - 4));
            offset = tmpOffset;
            return offset;
        }
    }
}
